package com.zhuhao.utils.filemoniter;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;

public class HolidayWatcher implements FileAlterationListener {

    private final File holidayPath;

    public HolidayWatcher(String holidayPath) {
        this.holidayPath = new File(holidayPath);
    }

    public void startWatching() throws Exception {
        // 构造观察类主要提供要观察的文件或目录
        FileAlterationObserver observer = new FileAlterationObserver(holidayPath);

        // 为观察对象添加收听对象
        observer.addListener(this);

        // 创建监控器
        FileAlterationMonitor monitor = new FileAlterationMonitor(1000); // 每秒检查一次

        // 添加观察者到监控器
        monitor.addObserver(observer);

        // 启动监控器
        monitor.start();

        // 为了让程序持续运行，这里添加一个无限循环
        while (true) {
            Thread.sleep(1000); // 每秒休眠1秒
        }
    }

    @Override
    public void onStart(FileAlterationObserver fileAlterationObserver) {
        System.out.println("Start watching...");
    }

    @Override
    public void onDirectoryCreate(File file) {

    }

    @Override
    public void onDirectoryChange(File file) {

    }

    @Override
    public void onDirectoryDelete(File file) {

    }

    @Override
    public void onFileCreate(File file) {
        System.out.println("File created: " + file.getAbsolutePath());
    }

    @Override
    public void onFileChange(File file) {
        System.out.println("File changed: " + file.getAbsolutePath());
    }

    @Override
    public void onFileDelete(File file) {
        System.out.println("File deleted: " + file.getAbsolutePath());
    }

    @Override
    public void onStop(FileAlterationObserver fileAlterationObserver) {

    }

    public static void main(String[] args) throws Exception {
        String pathToWatch = "D:\\customHoliday.properties"; // 替换为你想要监控的路径
        HolidayWatcher watcher = new HolidayWatcher(pathToWatch);
        watcher.startWatching();
    }
}
